package com.zhj.common.web.exception;

import com.zhj.common.core.result.Result;
import com.zhj.common.core.result.enums.Codes;
import com.zhj.common.core.util.ResultUtils;
import com.zhj.common.web.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 处理Controller的异常
 * @author zhj
 */
@Slf4j
@RestControllerAdvice
public class GlobalException  {

    /**
     * 默认异常处理
     * @return
     */
    @ExceptionHandler
    public Result globalExceptionHandler(Throwable t) {
        log.error("{Global-Exception} - 捕获到全局异常信息!");
        HttpServletRequest request = HttpUtils.getRequest();
        String url = request.getRequestURL().toString();
        log.error("{Global-Exception} - 请求的url - {}", url);
        log.error("{Global-Exception} - 异常信息:", t);
        return ResultUtils.createFail(Codes.SERVER_EXCEPTION);
    }

    /**
     * 业务异常处理
     * @return
     */
    @ExceptionHandler(ServiceException.class)
    public Result serviceExceptionHandler(ServiceException e) {
        log.error("{Service-Exception} - 捕获到业务异常信息!");
        HttpServletRequest request = HttpUtils.getRequest();
        String url = request.getRequestURL().toString();
        log.error("{Service-Exception} - 请求的url - {}", url);
        log.error("{Service-Exception} - 异常信息:", e);
        return ResultUtils.createFail(e.getCode(), e.getMsg());
    }

    /**
     * 断言异常处理
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result illegalArgumentExceptionHandler(IllegalArgumentException e) {
        log.error("{IllegalArgument-Exception} - 捕获到业务异常信息!");
        HttpServletRequest request = HttpUtils.getRequest();
        String url = request.getRequestURL().toString();
        log.error("{IllegalArgument-Exception} - 请求的url - {}", url);
        log.error("{IllegalArgument-Exception} - 异常信息:", e);
        return ResultUtils.createFail(Codes.PARAMETER_ERROR.code, e.getMessage());
    }

    /**
     * 参数异常处理
     * @return
     */
    @ExceptionHandler({BindException.class})
    public Result bindExceptionHandler(BindException e) {
        Set<String> msg = e.getBindingResult().getAllErrors().stream().map(objectError -> objectError.getDefaultMessage()).collect(Collectors.toSet());
        return ResultUtils.createFail(Codes.PARAMETER_ERROR, msg);
    }
}
